package com.hsnn.medstgmini.base.dict.controller;

import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hsnn.medstgmini.Constants;
import com.hsnn.medstgmini.base.dict.service.DicPharManager;
import com.hsnn.medstgmini.sys.model.SysUser;
import com.hsnn.medstgmini.util.ExcelUtil;
import com.hsnn.medstgmini.util.Pagination;

/**
 * @category 药理分类字典
 * @author CCL
 */
@Controller
@RequestMapping("/dicPhar")
public class DicPharController {

	private static final Logger log = Logger.getLogger(DicPharController.class);

	@Autowired
	private DicPharManager dicPharManager;

	@Autowired
	private HttpServletRequest request;

	/**
	 * @category 跳转药理分类字典列表页面
	 * @param model
	 * @return
	 */
	@RequestMapping("/toList")
	public String dicPharList(Model model) {
		return "/base/dict/pharList";
	}




	
	/**
	 * @category 保存编辑的药理分类
	 * @param dicPhar
	 * @return
	 */
	@RequestMapping("/edit")
	@ResponseBody
	public Pagination editSave(){
		printParams();
		Pagination page = new Pagination();
		try {
			String pharCode = request.getParameter("pharCode");
			String pharName = request.getParameter("pharName");
			String pharId = request.getParameter("pharId");
			if(StringUtils.isBlank(pharCode)){
				page.setMsg("编码不能为空!");
				page.setSuccess(false);
				return page;
			}
			if(StringUtils.isBlank(pharCode)){
				page.setMsg("名称不能为空!");
				page.setSuccess(false);
				return page;
			}
			List<Object> list1 = dicPharManager.checkRepeat("phar_code", pharCode, pharId);
			if(list1!=null&&list1.size()>0){
				page.setMsg("该编码已存在!");
				page.setSuccess(false);
				return page;
			}
			page.getConditions().put("pharCode", pharCode);
			
			List<Object> list2 = dicPharManager.checkRepeat("phar_name", pharName, pharId);
			if(list2!=null&&list2.size()>0){
				page.setMsg("该名称已存在!");
				page.setSuccess(false);
				return page;
			}
			page.getConditions().put("pharName", pharName);
			page.getConditions().put("pharId", pharId);
			SysUser user = (SysUser) request.getSession().getAttribute(Constants.USERINFO);
			page.getConditions().put("updUser", user.getId());
			dicPharManager.editSave(page);
			page.setSuccess(true);
		} catch (Exception e) {
			page.setSuccess(false);
			page.setMsg("数据异常");
			e.printStackTrace();
		}
		
		return page;
	}
	
	/**
	 * @category 保存新增的药理分类
	 * @param dicPhar
	 * @return
	 */
	@RequestMapping("/add")
	@ResponseBody
	public Pagination addSave(){
		printParams();
		Pagination page = new Pagination();
		try {
			String pharCode = request.getParameter("pharCode");
			String pharName = request.getParameter("pharName");
			String fatherId = request.getParameter("fatherId");
			if(StringUtils.isBlank(pharCode)){
				page.setMsg("编码不能为空!");
				page.setSuccess(false);
				return page;
			}
			if(StringUtils.isBlank(pharCode)){
				page.setMsg("名称不能为空!");
				page.setSuccess(false);
				return page;
			}
			List<Object> list1 = dicPharManager.checkRepeat("phar_code", pharCode, "");
			if(list1!=null&&list1.size()>0){
				page.setMsg("该编码已存在!");
				page.setSuccess(false);
				return page;
			}
			page.getConditions().put("pharCode", pharCode);
			
			List<Object> list2 = dicPharManager.checkRepeat("phar_name", pharName, "");
			if(list2!=null&&list2.size()>0){
				page.setMsg("该名称已存在!");
				page.setSuccess(false);
				return page;
			}
			page.getConditions().put("pharName", pharName);
			page.getConditions().put("fatherId", fatherId);
			SysUser user = (SysUser) request.getSession().getAttribute(Constants.USERINFO);
			page.getConditions().put("updUser", user.getId());
			dicPharManager.addSave(page);
			page.setSuccess(true);
		} catch (Exception e) {
			page.setSuccess(false);
			page.setMsg("数据异常");
			e.printStackTrace();
		}
		
		return page;
	}
	
	/**
	 * @category 跳转药理分类维护记录列表页面
	 * @param model
	 * @param id
	 * @return
	 */
	@RequestMapping("/log")
	public String dicPharLogList(Model model, String id) {
		printParams();
		model.addAttribute("id", id);
		request.setAttribute("pharCode", request.getParameter("pharCode"));
		try {
			String pharName = new String(request.getParameter("pharName").getBytes("ISO8859-1"),"utf-8");
			request.setAttribute("pharName", pharName);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return "/base/dict/pharLogList";
	}

	/**
	 * @category 查询药理分类维护记录列表
	 * @param result
	 * @param dicPhar
	 * @return
	 */
	@RequestMapping("/getDicPharLogList")
	@ResponseBody
	public Pagination getDicPharLogList() {
		printParams();
		Pagination page = new Pagination(request);
		String startTime = request.getParameter("startTime");
		String endTime = request.getParameter("endTime");
		if(StringUtils.isNotBlank(startTime)){
			page.getConditions().put("startTime", startTime);
		}
		if(StringUtils.isNotBlank(endTime)){
			page.getConditions().put("endTime", endTime);
		}
		try {
			page.getConditions().put("pharId", request.getParameter("pharId"));
			dicPharManager.getDicPharLogList(page);
		} catch (Exception e) {
			log.error("",e);
		}
		return page;
	}
	
	/**
	 * @category 查询药理分类列表
	 * @param result
	 * @param dicPhar
	 * @return
	 */
	@RequestMapping("/getDrugPharList")
	@ResponseBody
	public JSONObject getDrugPharList() {
		printParams();
		Pagination page = new Pagination(request);
		JSONObject objson= null;
		String fatherId = request.getParameter("parentid");
		String pharId = request.getParameter("nodeid");
		String leve = request.getParameter("n_level");
		String pharCode = request.getParameter("pharCode");
		String pharName = request.getParameter("pharName");
		String status = request.getParameter("status");
		boolean isLoaded = true;//是否加载子节点
		if(StringUtils.isNotBlank(fatherId)){
			page.getConditions().put("fatherId", fatherId);
		}
		if(StringUtils.isNotBlank(pharId)){
			page.getConditions().put("pharId", pharId);
		}
		if(StringUtils.isNotBlank(leve)){
			page.getConditions().put("leve", leve);
		}
		if(StringUtils.isNotBlank(pharCode)){
			page.getConditions().put("pharCode", pharCode.trim());
		}
		if(StringUtils.isNotBlank(pharName)){
			page.getConditions().put("pharName", pharName.trim());
			isLoaded = false; //当模糊查询时，子节点自动加载
		}
		if(StringUtils.isNotBlank(status)){
			page.getConditions().put("status", status);
			isLoaded = false; //子节点自动加载
		}
		try {
			objson = dicPharManager.getDicPharList(page,isLoaded);
		} catch (Exception e) {
			log.error("",e);
		}
		return objson;
	}
	
	/**
	 * @category 跳转药理分类日志详情页面
	 * @param model
	 * @return
	 */
	@RequestMapping("/toPharLogDetail")
	public String toPharLogDetail() {
		printParams();
		log.info("enter toPharLogDetail method!");
		List<Map<String,Object>> list = dicPharManager.getPharLogDetail(request.getParameter("logId"));
		request.setAttribute("list", list);
		return "/base/dict/pharLogDetail";
	}
	
	/**
	 * @category 启用|停用
	 * @param model
	 * @return page
	 */
	@RequestMapping(value={"/enable","/disable"})
	@ResponseBody
	public Pagination changeStatus(){
		printParams();
		Pagination page = new Pagination();
		String array = request.getParameter("array");
		String status = request.getParameter("status");
		StringBuffer  hierarchys = new StringBuffer();
		try {
				SysUser user = (SysUser) request.getSession().getAttribute(Constants.USERINFO);
				String updUser = user.getId();
				page.getConditions().put("updUser", updUser);
				if (StringUtils.isNotBlank(array)) {
					Gson gson = new Gson();
					Type type = new TypeToken<List<String>>() {
					}.getType();
					List<String> list = gson.fromJson(array, type);
					if (list != null && list.size()>0) {
						for(int i = 0;i<list.size();i++){
							hierarchys.append("^").append(list.get(i)).append("|");
						}
						hierarchys.deleteCharAt(hierarchys.length()-1);
						page.getConditions().put("hierarchys", hierarchys.toString());
						page.setForm(list);
					}else{
						page.setSuccess(false);
						return page;
					}
				}
				if(StringUtils.isNotBlank(status)){
					page.getConditions().put("status", status);
				}else{
					page.setSuccess(false);
					return page;
				}
				dicPharManager.changeStatus(page);
				page.setSuccess(true);
		} catch (Exception e) {
			page.setSuccess(false);
			e.printStackTrace();
		}
		return page;
	}
	
	/**
	 * 
	 *@category 获取参数打印
	 *@author wangbing
	 *@date 2015年6月9日
	 *Pagination
	 */
	@SuppressWarnings("rawtypes")
	public void printParams(){
		Enumeration paramNames = request.getParameterNames();
		try {
			while (paramNames.hasMoreElements()) {
				String paramName = (String) paramNames.nextElement();
				String paramValue = request.getParameter(paramName);
				log.info(paramName+":"+paramValue);
			}
		} catch (Exception e) {
			log.error("",e);
		}
	}
	
	/**
	 * 
	 *@category 导出excel
	 *@author wangbing
	 *@date 2015年6月9日
	 *Pagination
	 */
	@RequestMapping("exportExcel")
	@ResponseBody
	public Pagination exportExcel(HttpServletResponse response,String fileName){
		printParams();
		Pagination page = new Pagination();
		String pharCode = request.getParameter("pharCode");
		String pharName = request.getParameter("pharName");
		String status = request.getParameter("status");
		if(StringUtils.isNotBlank(pharCode)){
			page.getConditions().put("pharCode", pharCode.trim());
		}
		if(StringUtils.isNotBlank(pharName)){
			page.getConditions().put("pharName", pharName.trim());
		}
		if(StringUtils.isNotBlank(status)){
			page.getConditions().put("status", status.trim());
		}
		try {
			response.addHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes("GB2312"),"iso8859-1")); 
			OutputStream os= new BufferedOutputStream(response.getOutputStream());  
			 response.setContentType("application/vnd.ms-excel;charset=utf-8");  
			 dicPharManager.getDicPharNoPage(page);
			 String title = "药理分类";
			 String[] headers = {"编码","名称","状态"};
			 String[] alias = {"pharCode","pharName","status"};
			 ExcelUtil.exportExcel(page, os, title, headers, alias);
		} catch (Exception e) {
			page.setSuccess(false);
			e.printStackTrace();
		}
		return page;
	}
}
